package com.esyoga.yoyoga.service.impl;


import com.esyoga.yoyoga.mapper.*;

import com.esyoga.yoyoga.pojo.*;
import com.esyoga.yoyoga.pojo.DTO.GymOrdersDTO;
import com.esyoga.yoyoga.pojo.DTO.TrainerAgreementDTO;
import com.esyoga.yoyoga.service.GymService;
import com.esyoga.yoyoga.service.TrainerService;
import lombok.Data;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.esyoga.yoyoga.mapper.TGymMapper;
import com.esyoga.yoyoga.pojo.TGym;
import com.esyoga.yoyoga.pojo.TGymExample;
import com.esyoga.yoyoga.service.GymService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/*
场馆service实现
 */
@Data
@Service("gymService")
@Transactional
public class GymServiceImpl implements GymService {

    @Resource
    private TTrainerAgreementMapper tTrainerAgreementMapper;
    @Resource
    private TTrainerAgreementExample tTrainerAgreementExample;
    @Resource
    private TTrainerMapper tTrainerMapper;
    @Resource
    private TTrainerExample tTrainerExample;
    @Resource
    private TGymMapper tGymMapper;
    @Resource
    private TGymExample tGymExample;
    @Resource
    private TEvaluationExample tEvaluationExample;
    @Resource
    private TEvaluationMapper tEvaluationMapper;
    @Resource
    private TGymAgreementMapper tGymAgreementMapper;
    @Resource
    private TGymAgreementExample tGymAgreementExample;
    @Resource
    private TInformMapper tInformMapper;
    @Resource
    private TOrderMapper tOrderMapper;
    @Resource
    private TOrderExample tOrderExample;
    @Resource
    private TContractExample tContractExample;
    @Resource
    private TContractMapper tContractMapper;
    @Resource
    private TrainerService trainerService;
    @Resource
    private TStudentMapper tStudentMapper;

    /*通过场馆id找到所有与此场馆签约的教练（教练不能是被禁用的）*/
    @Override
    public List<TTrainer> findTrainersByGymid(int gid) {
        //添加条件
        tTrainerAgreementExample.clear();
        TTrainerAgreementExample.Criteria criteria=tTrainerAgreementExample.createCriteria();
        criteria.andTaGIdEqualTo(gid).andTaStateEqualTo(4);
        //查出所有符合条件的合约
        List<TTrainerAgreement> tTrainerAgreements=tTrainerAgreementMapper.selectByExample(tTrainerAgreementExample);
        //取出这些合约里的教练id
        List<Integer> tids=new ArrayList<>();
        for (TTrainerAgreement tTrainerAgreement:tTrainerAgreements) {
            tids.add(tTrainerAgreement.getTaTId());
        }
        //查询得到所有该场馆签约教练信息
        List<TTrainer> tTrainers=new ArrayList<>();
        if(tids.size()!=0&&tids!=null){
            tTrainerExample.clear();
            TTrainerExample.Criteria criteria1=tTrainerExample.createCriteria();
            //教练状态不能是禁用
            criteria1.andTIdIn(tids).andTStateNotEqualTo(2);
            tTrainers=tTrainerMapper.selectByExample(tTrainerExample);
        }
        return tTrainers;
    }

    /*通过场馆id找所有教练签约订单*/
    @Override
    public List<TrainerAgreementDTO> findTTrainerAgreementsByGymid(int gid) {
        tTrainerAgreementExample.clear();
        TTrainerAgreementExample.Criteria criteria=tTrainerAgreementExample.createCriteria();
        criteria.andTaGIdEqualTo(gid).andTaStateEqualTo(0);
        List<TTrainerAgreement> tTrainerAgreements=tTrainerAgreementMapper.selectByExample(tTrainerAgreementExample);
        List<TrainerAgreementDTO> trainerAgreementDTOS=new ArrayList<>();
        for (TTrainerAgreement t:tTrainerAgreements) {
            TrainerAgreementDTO trainerAgreementDTO=new TrainerAgreementDTO(trainerService.selectTrainerById(t.getTaTId()).gettName(),t);
            trainerAgreementDTOS.add(trainerAgreementDTO);
        }
        return trainerAgreementDTOS;
    }

    /*根据签约id签约或拒绝教练*/
    @Override
    public void contractAudit(int taid, int flag){
        /*找到签约表*/
        TTrainerAgreement tTrainerAgreement=tTrainerAgreementMapper.selectByPrimaryKey(taid);
        /*取时间*/
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime=simpleDateFormat.format(new Date());
        /*取教练id和场馆名（用来发送通知）*/
        int tid=tTrainerAgreement.getTaTId();
        tTrainerAgreement.setTaId(taid);
        String gname=tGymMapper.selectByPrimaryKey(tTrainerAgreement.getTaGId()).getgName();
        /*如果选择签约*/
        if(flag==1){
            tTrainerAgreement.setTaState(4);
            tTrainerAgreement.setTaCreatetime(nowTime);
            tTrainerAgreement.setTaUpdatetime(nowTime);
            //更新签约状态
            tTrainerAgreementMapper.updateByPrimaryKeySelective(tTrainerAgreement);
            //添加签约成功通知
            TInform tInform=new TInform();
            tInform.setiUserid(tid);
            tInform.setiUsertype(1);
            tInform.setiText("恭喜您，您与"+gname+"的签约成功了！");
            tInform.setiTime(nowTime);
            tInformMapper.insertSelective(tInform);
        }else{
            /*选择拒绝*/
            tTrainerAgreement.setTaState(2);
            tTrainerAgreement.setTaUpdatetime(nowTime);
            //更新签约状态
            tTrainerAgreementMapper.updateByPrimaryKeySelective(tTrainerAgreement);
            //添加被场馆拒绝的通知
            TInform tInform=new TInform();
            tInform.setiUserid(tid);
            tInform.setiUsertype(1);
            tInform.setiText("很遗憾，"+gname+"拒绝了您的签约审核");
            tInform.setiTime(nowTime);
            tInformMapper.insertSelective(tInform);
        }

    }

    /*查看场馆的所有订单*/
    @Override
    public List<GymOrdersDTO> findOrdersByGymid(int gid) {
        /*先从合约表里找到所有与此场馆有关的合约id*/
        tContractExample.clear();
        TContractExample.Criteria criteriaContract=tContractExample.createCriteria();
        criteriaContract.andCGIdEqualTo(gid);
        List<TContract> tContracts = tContractMapper.selectByExample(tContractExample);
        List<Integer> ocids=new ArrayList<>();
        for (TContract c:tContracts) {
            ocids.add(c.getcId());
        }
        /*用合约id查所有的订单*/
        tOrderExample.clear();
        TOrderExample.Criteria criteriaOrder=tOrderExample.createCriteria();
        criteriaOrder.andOCIdIn(ocids);
        if(ocids.size()==0){
            return null;
        }
        List<TOrder> orders=tOrderMapper.selectByExample(tOrderExample);
        List<GymOrdersDTO> gymOrdersDTOS=new ArrayList<>();
        for (TOrder o:orders) {
            TContract tContract=tContractMapper.selectByPrimaryKey(o.getoCId());
            int sid=tContract.getcSId();
            String sName=tStudentMapper.selectByPrimaryKey(sid).getsName();
            int tid=tContract.getcTId();
            String tName=tTrainerMapper.selectByPrimaryKey(tid).gettName();
            GymOrdersDTO gymOrdersDTO=new GymOrdersDTO(sName,tName,o);
            gymOrdersDTOS.add(gymOrdersDTO);
        }

        return gymOrdersDTOS;
    }

    /*场馆与教练解约*/
    @Override
    public void rescissionWithTrainer(int gid, int tid) {
        String gname=tGymMapper.selectByPrimaryKey(gid).getgName();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime=simpleDateFormat.format(new Date());
        //在教练签约表里找到唯一的这个签约表
        tTrainerAgreementExample.clear();
        TTrainerAgreementExample.Criteria criteria=tTrainerAgreementExample.createCriteria();
        criteria.andTaGIdEqualTo(gid).andTaTIdEqualTo(tid).andTaStateEqualTo(4);
        //设置要更新的值（签约状态改为5，设置更新时间）
        TTrainerAgreement tTrainerAgreement=new TTrainerAgreement();
        tTrainerAgreement.setTaState(5);
        tTrainerAgreement.setTaUpdatetime(nowTime);
        //更新
        tTrainerAgreementMapper.updateByExampleSelective(tTrainerAgreement,tTrainerAgreementExample);
        //添加签约成功通知
        TInform tInform=new TInform();
        tInform.setiUserid(tid);
        tInform.setiUsertype(1);
        tInform.setiText("您与"+gname+"的签约关系已解除！");
        tInform.setiTime(nowTime);
        tInformMapper.insertSelective(tInform);
    }

    /*查余额*/
    @Override
    public BigDecimal findBalanceByGid(int gid) {
        return tGymMapper.selectByPrimaryKey(gid).getgBanlance();
    }

    /*场馆发起与平台签约的请求*/
    @Override
    public String applicationForSignature(int gid,double platformratio,BigDecimal joinBanlance) {
        BigDecimal gymBalance=findBalanceByGid(gid);
        if (gymBalance.compareTo(joinBanlance)<0){
            return "场馆账户中没有足够的余额支付平台入驻费用，请及时充值";
        }
        /*把场馆的钱划出来*/
        TGym tGym=new TGym();
        tGym.setgId(gid);
        tGym.setgBanlance(gymBalance.subtract(joinBanlance));
        tGymMapper.updateByPrimaryKeySelective(tGym);
        /*添加场馆平台签约表*/
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime=simpleDateFormat.format(new Date());
        TGymAgreement tGymAgreement=new TGymAgreement();
        tGymAgreement.setGaGId(gid);
        tGymAgreement.setGaPlatformratio(platformratio);
        tGymAgreement.setGaJoinbanlance(joinBanlance);
        tGymAgreement.setGaState(0);
        tGymAgreement.setGaSigntime(nowTime);
        tGymAgreement.setGaUpdatetime(nowTime);
        tGymAgreementMapper.insertSelective(tGymAgreement);
        return "请求已经发送，我们会尽快回复";
    }

    @Override
    public TGym findGymByGid(int gid) {
        return tGymMapper.selectByPrimaryKey(gid);
    }

    @Override
    public String InformationModify(TGym tGym) {
        tGymMapper.updateByPrimaryKeySelective(tGym);
        return "修改成功";
    }

    /*计算教练的星级*/
    @Override
    public BigDecimal countStarForTrainer(int tid) {
        /*找到教练的所有评论*/
        tEvaluationExample.clear();
        TEvaluationExample.Criteria criteria=tEvaluationExample.createCriteria();
        criteria.andETIdEqualTo(tid);
        List<TEvaluation> tEvaluations= tEvaluationMapper.selectByExample(tEvaluationExample);
        int count=0;
        for (TEvaluation e:tEvaluations) {
            count+=e.geteStar();
        }
        if(tEvaluations.size()!=0){
            BigDecimal bCount=new BigDecimal(count);
            BigDecimal size=new BigDecimal(tEvaluations.size());
            BigDecimal star=bCount.divide(size,10,BigDecimal.ROUND_HALF_UP);
            return star.setScale(1,BigDecimal.ROUND_HALF_UP);
        }
        return null;
    }


    @Override
    public List<TGym>findAllGyms(String gName) {
        tGymExample.clear();
       TGymExample.Criteria criteria= tGymExample.createCriteria();
       //模糊匹配前端名字
        criteria.andGNameLike(gName);
        //限定查询已签约的
        criteria.andGStateEqualTo(0);

       List<TGym> tGyms= tGymMapper.selectByExample(tGymExample);
        return tGyms;
    }

    @Override
    public List<TTrainer> findAllTrainersByGymId(Integer gId) {
        List<Integer> tids=new ArrayList<Integer>();
        //通过场馆id在私教和场馆签约表查询该场馆下的所有私教，获得其id，在查询他们的信息
        tTrainerAgreementExample.clear();
        TTrainerAgreementExample.Criteria criteria= tTrainerAgreementExample.createCriteria();
        criteria.andTaGIdEqualTo(gId);
        //此合约状态必须为签约成功
        criteria.andTaStateEqualTo(4);
        //获取所有合约信息，取出私教id
       List<TTrainerAgreement> tTrainerAgreements= tTrainerAgreementMapper.selectByExample(tTrainerAgreementExample);
        for (TTrainerAgreement tTrainerAgreement:tTrainerAgreements
             ) {
            tids.add(tTrainerAgreement.getTaTId());
        }
        //将上面已获得该场馆下私教的所有id用来查询,并且此私教状态审核通过的
        tTrainerExample.clear();
       TTrainerExample.Criteria criteria1= tTrainerExample.createCriteria();
        criteria1.andTIdIn(tids);
        criteria1.andTStateEqualTo(1);
        List<TTrainer> tTrainers= tTrainerMapper.selectByExample(tTrainerExample);
        return tTrainers;
    }

    /**
     *
     * @return
     */
    @Override
    public List<TGym> selectTGyms() {

        PageHelper.startPage(1, 5);
        tGymExample.clear();
        List<TGym> tGyms = tGymMapper.selectByExample(tGymExample);
        return null;
    }

    /**
     * @param tGym
     * @return
     */
    @Override
    public int updateTGym(TGym tGym) {
        return tGymMapper.updateByPrimaryKeySelective(tGym);
    }

    /**
     * 增加或减少场馆余额
     * @param money:增加或减少的金额。正数为增加，负数为减少
     * @return
     */
    @Override
    public String updateTGymBalance(BigDecimal money, Integer gId) {
        //获取场馆的当前余额
        BigDecimal gymBalance = tGymMapper.selectByPrimaryKey(gId).getgBanlance();
        if(gymBalance==null){
            gymBalance = new BigDecimal(0);
        }
        //更新的金额
        BigDecimal gymUpdateBalance = gymBalance.add(money);
        //余额不足
        if(gymUpdateBalance.compareTo(new BigDecimal(0))<0){
            return "更新失败，余额不足";
        }
        //更新
        TGym tGym = new TGym();
        tGym.setgId(gId);
        tGym.setgBanlance(gymUpdateBalance);
        if(tGymMapper.updateByPrimaryKeySelective(tGym)>0){
            return "更新成功";
        }else{
            return "更新失败";
        }
    }


}
